package com.bit.blog.common.interceptor;


import com.bit.blog.common.constant.Constants;
import com.bit.blog.common.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 1. 获取token
         * 2. 校验token
         * 3. 返回
         */
        String userToken = request.getHeader(Constants.HEADER_USER_TOKEN_KEY);
        log.info("从header中获取到token. url:{}, userToken:{}", request.getRequestURI(),userToken);
        Boolean check = JwtUtils.check(userToken);
        if (check){
            return true;
        }
        log.error("token校验失败, token:{}", userToken);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        return false;
    }
}
